export class AlawEncoder {
  static encode(pcmSamples) {
    const encoded = new Uint8Array(pcmSamples.length);
    for (let i = 0; i < pcmSamples.length; i++) {
      const sample = pcmSamples[i];
      const sign = (sample >> 8) & 0x80;
      let absSample = sign ? ~sample : sample;
      absSample = (absSample >> 4) & 0x0FFF;
      let segment = 0;
      if (absSample >= 0x400) {
        segment = 7;
        absSample = (absSample >> 6) & 0x3F;
      } else {
        segment = 6;
        while (absSample >= (0x20 << segment)) {
          segment--;
        }
        absSample = (absSample >> (segment - 1)) & 0x1F;
      }
      const code = (segment << 4) | absSample;
      encoded[i] = sign ? code : code ^ 0xD5;
    }
    return encoded;
  }
}
